package com.dog.threesixty;

import java.io.File;
import java.io.InputStream;
import java.io.ObjectInputStream.GetField;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dog.share.twitter.TwitterShareManager;
import com.dog.utils.Constants;
import com.dog.utils.Downloader;
import com.dog.utils.NoRepeatRandom;
import com.dog.utils.Utils;
import com.fb.android.FacebookShareManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RecallQuizeActivity extends Activity implements OnClickListener {

	private RelativeLayout imageViewContainer;
	private RelativeLayout recallLayout;

	private Button mainMenuButton;
	private Button tryButton;
	private ImageView twitterButton;
	private Button quizeButton;
	private ImageView facebookButton;

	private ImageView pinView;
	private ImageView pauseView;
	private ImageView imageView;
	private ImageView animView;

	private TextView tView;
	private TextView quesTextView;
	private TextView alertView;
	private TextView timerView;
	private TextView scoreView;
	private TextView congratulationView;
	private TextView whatView;

	private boolean isTimer;
	private boolean isClick;
	private boolean isExit;
	private boolean isAnim;
	private boolean isNext = true;
	private boolean isFirstTime = true;
	private boolean isPinDrop;
	private boolean isNextLevel;
	private boolean isPause;
	private boolean isNextQuestion = true;
	private boolean isCorrect;

	private int currentIndex = -1;
	private int currentPosition = -1;
	private int score = 0;
	private int correctAnswer = 0;
	private int quizeIndex;
	private int randomValue;
	private int level;
	private int imageViewWidth;
	private int imageViewHeight;
	private int bonusScore;
	private int numOfQuestion;
	private int targetPosition[];
	private int imagesToShow[] = { R.drawable.dog1_2x, R.drawable.dog2_2x,
			R.drawable.dog3_2x, R.drawable.dog4_2x, R.drawable.dog5_2x,
			R.drawable.dog6_2x, R.drawable.dog7_2x, R.drawable.dog8_2x,
			R.drawable.dog9_2x, R.drawable.dog10_2x, R.drawable.dog11_2x,
			R.drawable.dog12_2x, R.drawable.dog13_2x, R.drawable.dog14_2x };

	private long remainingTime;

	private float factor;

	private String IMAGE_DIRECTORY;
	private String partFileName;

	private Bitmap bitmap;

	private NoRepeatRandom nrr;
	private CountDownTimer timer;
	private ImplementQuiz iquize;
	private File files[];
	private List<JSONArray> items;

	private boolean isFilesDownloaded[] = new boolean[18];
	private RelativeLayout mainLayout;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		try {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_recall);

			isFilesDownloaded = Utils
					.getFilesDownloaded(RecallQuizeActivity.this);

			bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.pin_drop);
			
			getJSONObjectForRandomLevel();

			mainLayout = (RelativeLayout) findViewById(R.id.main_layout);
			recallLayout = (RelativeLayout) findViewById(R.id.recallLayout);
			imageViewContainer = (RelativeLayout) findViewById(R.id.image_view_container);

			level = getIntent().getIntExtra(Constants.KEY_LEVEL, 0);

			items = new ArrayList<JSONArray>();

			dropPin();

			alertView = (TextView) findViewById(R.id.alertView);
			timerView = (TextView) findViewById(R.id.timerView);
			scoreView = (TextView) findViewById(R.id.scoreView);
			quesTextView = (TextView) findViewById(R.id.questionNumberView);
			tView = (TextView) findViewById(R.id.tView);
			congratulationView = (TextView) findViewById(R.id.congratulationView);
			imageView = (ImageView) findViewById(R.id.imageView);
			pauseView = (ImageView) findViewById(R.id.pauseView);
			pauseView.setOnClickListener(this);

			whatView = (TextView) findViewById(R.id.whatView);

			quizeButton = (Button) findViewById(R.id.quizeButton);

			mainMenuButton = (Button) findViewById(R.id.mainMenuButton);
			mainMenuButton.setOnClickListener(this);

			tryButton = (Button) findViewById(R.id.tryButton);
			tryButton.setOnClickListener(this);

			twitterButton = (ImageView) findViewById(R.id.twitterButton);
			twitterButton.setOnClickListener(this);

			facebookButton = (ImageView) findViewById(R.id.facebookButton);
			facebookButton.setOnClickListener(this);

			isTimer = getIntent()
					.getBooleanExtra(Constants.KEY_IS_TIMER, false);
			if (!isTimer) {
				timerView.setVisibility(View.INVISIBLE);
				tView.setVisibility(View.INVISIBLE);
			}

			getPointsList(level);
			Log.i("DREG", "Size =" + items.size());

			files = Downloader.getFileList(IMAGE_DIRECTORY);

			imageView.setOnTouchListener(new View.OnTouchListener() {
				@Override
				public boolean onTouch(View arg0, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						if (isClick) {
							if (isTimer) {
								timer.cancel();
							}
							posX = (int) event.getX();
							posY = (int) event.getY();
							Log.i("DREG", "X =" + posX + " Y =" + posY);
							implementQuiz();

						}
						break;
					}
					return false;
				}
			});

			imageViewContainer.post(new Runnable() {

				@Override
				public void run() {
					factor = Math.min(imageViewContainer.getWidth() / 480.0f,
							imageViewContainer.getHeight() / 300.0f);
					recallLayout.getLayoutParams().width = imageView
							.getLayoutParams().width = imageViewWidth = (int) (480 * factor);
					recallLayout.getLayoutParams().height = imageView
							.getLayoutParams().height = imageViewHeight = (int) (300 * factor);
					// showQuizeAimation();
					playQuiz();

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public class ImplementQuiz extends AsyncTask<String, String, String> {
		private int currentIndex;
		private long waitingTime;

		public ImplementQuiz(int currentIndex, long waitingTime) {
			super();
			this.currentIndex = currentIndex;
			this.waitingTime = waitingTime;
		}

		protected void onProgressUpdate(String... arg0) {
			try {

				if (isPinDrop) {
					ViewGroup vg = (ViewGroup) (pinView.getParent());
					vg.removeView(pinView);
					isPinDrop = false;
				}
				pauseView.setEnabled(true);
				quizeIndex = currentIndex;
				currentIndex++;
				currentPosition = currentIndex;
				quizeButton.setVisibility(View.VISIBLE);
				quizeButton.setBackgroundResource(R.drawable.quize_button);
				quizeButton.setTextColor(Color.WHITE);
				quizeButton.setEnabled(true);
				whatView.setText("Touch the correct part or image?");

				if (currentIndex < ja.length()) {

					Log.i("DREG", "Current Index=" + currentIndex);
					if (isTimer) {
						showTimer(waitingTime);
					}

					isCorrect = false;
					isClick = true;
					quesTextView
							.setText((currentIndex + 1) + "/" + ja.length());

					String fileName = ja.getJSONObject(
							targetPosition[currentIndex]).getString("-parent");
					partFileName = ja.getJSONObject(
							targetPosition[currentIndex]).getString("-part");
					Bitmap bm = BitmapFactory.decodeFile(getFilePath(fileName));
					Bitmap ret = Bitmap.createBitmap(imageViewWidth,
							imageViewHeight, Bitmap.Config.ARGB_8888);
					Canvas comboImage = new Canvas(ret);
					Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
					Rect r2 = new Rect(0, 0, imageViewWidth, imageViewHeight);
					comboImage.drawBitmap(bm, r1, r2, null);
					comboImage.save();
					imageView.setImageBitmap(ret);

					String partName = ja.getJSONObject(
							targetPosition[currentIndex]).getString("-part");
					quizeButton.setText(partName);
					if (currentIndex < (ja.length() - 1)) {
						waitingTime = 10000;
					} else {
						waitingTime = 500;
					}

				} else {
					timerView.setVisibility(View.GONE);
					tView.setVisibility(View.INVISIBLE);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected String doInBackground(String... arg0) {
			try {

				while ((currentIndex < ja.length()) && (!isExit)) {
					if (isTimer) {
						Random random = new Random();
						randomValue = random.nextInt(4);
						if (!isPause) {
							publishProgress("");
						}
						Thread.sleep(waitingTime);
					} else {
						if (isNextQuestion) {
							isNextQuestion = false;
							Random random = new Random();
							randomValue = random.nextInt(4);
							if (currentIndex != -1) {
								Thread.sleep(Constants.POST_CLICK_TIME);
							}
							publishProgress("");
							Thread.sleep(Constants.PRE_CLICK_TIME);

						}
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String unused) {

			int percent = (int) ((correctAnswer * 100) / (ja.length()));
			// quesTextView.setVisibility(View.GONE);
			imageView.setBackgroundColor(Color.parseColor("#313131"));
			mainLayout.setBackgroundColor(Color.parseColor("#313131"));
			imageView.setAlpha(0x88);
			timerView.setText("0.0");
			quizeButton.setVisibility(View.INVISIBLE);
			mainMenuButton.setVisibility(View.VISIBLE);
			tryButton.setVisibility(View.VISIBLE);
			facebookButton.setVisibility(View.VISIBLE);
			twitterButton.setVisibility(View.VISIBLE);
			alertView.setVisibility(View.VISIBLE);
			// pauseView.setVisibility(View.INVISIBLE);
			if (percent < 70) {
				isNextLevel = false;
				congratulationView.setText("Sorry :)");
				alertView.setText("You only scored " + score + " points with "
						+ percent + "% accuracy.");
			}

			else {
				isNextLevel = true;
				tryButton.setText("Next Level");
				congratulationView.setText("Congratulations !");
				alertView.setText("You have scored " + score + " points with "
						+ percent + "% accuracy.");
				int highestScore = Utils.getLevelHighestScore(
						RecallQuizeActivity.this, Constants.KEY_RECALL_SCORE
								+ level);
				if (score > highestScore) {
					Utils.putLevelHighestScore(RecallQuizeActivity.this,
							Constants.KEY_RECALL_SCORE + level, score);
					Utils.putPrecentage(RecallQuizeActivity.this,
							Constants.KEY_RECALL_PERCENTAGE + level, percent);
				}

			}
		}
	}

	private void playQuiz() {
		getJsonData(level);
		// showQuizeAimation();
		iquize = new ImplementQuiz(currentPosition, Constants.WAITING_TIME);
		iquize.execute();
	}

	private String getFilePath(String fileName) {
		boolean isFound = false;
		fileName = fileName + ".png";
		String path = "";

		if (!isFound) {
			File pack1File[] = Downloader
					.getFileList(Constants.PACK1_DIRECTORY);
			if (pack1File != null) {
				for (int i = 0; i < pack1File.length; i++) {
					if (pack1File[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = pack1File[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File pack2File[] = Downloader
					.getFileList(Constants.PACK2_DIRECTORY);
			if (pack2File != null) {
				for (int i = 0; i < pack2File.length; i++) {
					if (pack2File[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = pack2File[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File pack3File[] = Downloader
					.getFileList(Constants.PACK3_DIRECTORY);

			if (pack3File != null) {
				for (int i = 0; i < pack3File.length; i++) {
					if (pack3File[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = pack3File[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File pack4File[] = Downloader
					.getFileList(Constants.PACK4_DIRECTORY);

			if (pack4File != null) {
				for (int i = 0; i < pack4File.length; i++) {
					if (pack4File[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = pack4File[i].getAbsolutePath();
						return path;
					}
				}
			}
		}

		if (!isFound) {
			File pack5File[] = Downloader
					.getFileList(Constants.PACK5_DIRECTORY);
			if (pack5File != null) {
				for (int i = 0; i < pack5File.length; i++) {
					if (pack5File[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = pack5File[i].getAbsolutePath();
						return path;
					}
				}
			}
		}
		return path;
	}

	private String getJsonData(int level) {
		String jsonFileName = "";
		JSONObject jo;
		try {

			switch (level) {
			case 0:
				IMAGE_DIRECTORY = "pack1";
				jsonFileName = "General 1 Quiz 2 Answers.json";
				break;
			case 1:
				IMAGE_DIRECTORY = "pack1";
				jsonFileName = "General 2 Quiz 2 Answers.json";
				break;
			case 2:
				IMAGE_DIRECTORY = "pack1";
				jsonFileName = "General 3 Quiz 2 Answers.json";
				break;
			case 3:
				IMAGE_DIRECTORY = "pack1";
				jsonFileName = "Conformation 1 Quiz 2 Answers.json";
				break;
			case 4:
				IMAGE_DIRECTORY = "pack2";
				jsonFileName = "Conformation 2 Quiz 2 Answers.json";
				break;
			case 5:
				IMAGE_DIRECTORY = "pack2";
				jsonFileName = "Conformation 3 Quiz 2 Answers.json";
				break;
			case 6:
				IMAGE_DIRECTORY = "pack2";
				jsonFileName = "Conformation 4 Quiz 2 Answers.json";
				break;
			case 7:
				IMAGE_DIRECTORY = "pack2";
				jsonFileName = "Skeleton 1 Quiz 2 Answers.json";
				break;
			case 8:
				IMAGE_DIRECTORY = "pack3";
				jsonFileName = "Skeleton 2 Quiz 2 Answers.json";
				break;
			case 9:
				IMAGE_DIRECTORY = "pack3";
				jsonFileName = "Super Muscles 1 Quiz 2 Answers.json";
				break;
			case 10:
				IMAGE_DIRECTORY = "pack3";
				jsonFileName = "Super Muscles 2 Quiz 2 Answers.json";
				break;
			case 11:
				IMAGE_DIRECTORY = "pack4";
				jsonFileName = "Deep Muscles 1 Quiz 2 Answers.json";
				break;
			case 12:
				IMAGE_DIRECTORY = "pack4";
				jsonFileName = "Deep Muscles 2 Quiz 2 Answers.json";
				break;
			case 13:
				IMAGE_DIRECTORY = "pack4";
				jsonFileName = "Skull Quiz 2 Answers.json";
				break;
			case 14:
				IMAGE_DIRECTORY = "pack5";
				jsonFileName = "Teeth Quiz 2 Answers.json";
				break;
			case 15:
				IMAGE_DIRECTORY = "pack5";
				jsonFileName = "Organs 1 Quiz 2 Answers.json";
				break;
			case 16:
				IMAGE_DIRECTORY = "pack5";
				jsonFileName = "Organs 2 Quiz 2 Answers.json";
				break;
			case 17:
				IMAGE_DIRECTORY = "pack1";
				jsonFileName = "Random Quiz 2 Answers.json";
				break;

			default:
				jsonFileName = "Level 1-Quiz 2 Answers.json";
				break;
			}

			if (level != 17) {
				jo = new JSONObject(new String(Utils.getFileData(this,
						jsonFileName)));
			} else {
				jo = getJSONObjectForRandomLevel();
			}

			ja = jo.getJSONObject("root").getJSONArray("dog");
			numOfQuestion = ja.length();
			for (int k = 0; k < ja.length(); k++) {
				String fileName = ja.getJSONObject(k).getString("-parent");
				Log.i("DREG", "fileName = " + Utils.getFileName(fileName));
			}

			nrr = new NoRepeatRandom(0, ja.length() - 1);
			targetPosition = new int[ja.length()];

			for (int i = 0; i < ja.length(); i++) {
				targetPosition[i] = nrr.GetRandom();
			}

			Log.i("DREG", "jsonString=" + jo.toString());

			return jo.toString();
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			isExit = true;
			Intent intent = new Intent(RecallQuizeActivity.this,
					RecallBeforeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.facebookButton:
			faceBookSharing("I have just scored " + score + " in Horse 360");
			break;
		case R.id.twitterButton:
			shareInTwitter();
			break;
		case R.id.mainMenuButton:
			isExit = true;
			imageView.setAlpha(0xFF);
			Intent intent = new Intent(RecallQuizeActivity.this,
					RecallBeforeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		case R.id.tryButton:
			if (!isNextLevel) {
				currentIndex = -1;
				isExit = false;
				isNext = true;
				score = 0;
				scoreView.setText("" + score);
				imageView.setAlpha(0xFF);
				alertView.setVisibility(View.GONE);
				pauseView.setVisibility(View.VISIBLE);
				quizeButton.setVisibility(View.VISIBLE);
				quesTextView.setVisibility(View.VISIBLE);
				mainMenuButton.setVisibility(View.INVISIBLE);
				twitterButton.setVisibility(View.INVISIBLE);
				facebookButton.setVisibility(View.INVISIBLE);
				tryButton.setVisibility(View.INVISIBLE);
				// showQuizeAimation();
				Intent in = new Intent(RecallQuizeActivity.this,
						RecallQuizeActivity.class);
				in.putExtra(Constants.KEY_IS_TIMER, isTimer);
				in.putExtra(Constants.KEY_LEVEL, level);
				startActivity(in);
			} else {
				++level;

				// files = Downloader.getFileList(IMAGE_DIRECTORY);
				if (isFilesDownloaded[level]) {
					Intent i = new Intent(RecallQuizeActivity.this,
							RecallQuizeActivity.class);
					i.putExtra(Constants.KEY_IS_TIMER, isTimer);
					i.putExtra(Constants.KEY_LEVEL, level);
					i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
				} else {
					Intent backIntent = new Intent(RecallQuizeActivity.this,
							RecallBeforeActivity.class);
					backIntent.putExtra(Constants.KEY_NEXT_LEVEL, level);
					backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(backIntent);
				}
			}
			break;

		case R.id.pauseView:
			isPause = true;
			if (isTimer) {
				timer.cancel();
			}
			iquize.cancel(true);
			showPausePopUp();
			break;

		default:
			break;

		}

	}

	public void showAlertMessage(Context context, String title, String message) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setMessage(message).setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int id) {
						Intent backIntent = new Intent(
								RecallQuizeActivity.this,
								RecallBeforeActivity.class);
						backIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(backIntent);
					}
				});
		final AlertDialog alert = builder.create();
		alert.setTitle(title);
		alert.show();
	}

	private void showTimer(long waitingTime) {
		// timerView.setText("10.0");
		bonusScore = 0;
		timer = new CountDownTimer(waitingTime, 100) {

			@Override
			public void onTick(long millisUntilFinished) {
				String time = "";
				if (isClick) {
					bonusScore = (int) (Math
							.ceil((double) millisUntilFinished / 1000));
				}
				remainingTime = millisUntilFinished;

				long second = millisUntilFinished / 1000;
				long tenth = (millisUntilFinished % 1000) / 100;
				time = second + "." + tenth;
				timerView.setText(time);

			}

			@Override
			public void onFinish() {
				timerView.setText(0 + "." + 0);

			}
		}.start();
	}

	private void faceBookSharing(String message) {
		FacebookShareManager fsm = new FacebookShareManager(this, this,
				Constants.FACEBOOK_APP_ID, Constants.FACEBOOK_PERMISSION);
		fsm.shareMessage(message);

	}

	private void shareInTwitter() {
		TwitterShareManager tsm = new TwitterShareManager(
				RecallQuizeActivity.this, this);
		tsm.shareTweet("I have just score " + score + " in Horse 360");
	}

	private Bitmap getBitmap(String directory, String fileName) {
		boolean isFound = false;
		fileName = fileName + ".png";
		String path = "";

		if (!isFound) {
			File files[] = Downloader.getFileList(IMAGE_DIRECTORY);
			if (files != null) {
				for (int i = 0; i < files.length; i++) {
					if (files[i].getName().equalsIgnoreCase(fileName)) {
						isFound = true;
						path = files[i].getAbsolutePath();

					}
				}
			}
		}

		Bitmap bm = BitmapFactory.decodeFile(path);
		Bitmap ret = Bitmap.createBitmap(imageViewWidth, imageViewHeight,
				Bitmap.Config.ARGB_8888);
		Canvas comboImage = new Canvas(ret);
		Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
		Rect r2 = new Rect(0, 0, imageViewWidth, imageViewHeight);
		comboImage.drawBitmap(bm, r1, r2, null);
		comboImage.save();

		return ret;
	}

	private int posX = 0;
	private int posY = 0;
	private float widthFactor;
	private float heightFactor;

	private void implementQuiz() {

		pauseView.setEnabled(false);
		Bitmap bm = null;

		bm = BitmapFactory.decodeFile(getFilePath(partFileName));

		Bitmap ret = Bitmap.createBitmap(imageViewWidth, imageViewHeight,
				Bitmap.Config.ARGB_8888);
		Canvas comboImage = new Canvas(ret);
		Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
		Rect r2 = new Rect(0, 0, imageViewWidth, imageViewHeight);
		comboImage.drawBitmap(bm, r1, r2, null);
		comboImage.save();
		JSONArray points = items.get(targetPosition[currentPosition]);

		for (int i = 0; i < points.length(); i++) {
			try {
				int x1 = (int) (points.getJSONObject(i).getInt("-x1") * factor);
				int x2 = (int) (points.getJSONObject(i).getInt("-x2") * factor);
				int y1 = (int) (points.getJSONObject(i).getInt("-y1") * factor);
				int y2 = (int) (points.getJSONObject(i).getInt("-y2") * factor);
				// comboImage.drawRect(new Rect(x1,y1,x2,y2 ),paint);
				if ((posX >= x1 && posX <= x2) && (posY >= y1 && posY <= y2)) {
					isCorrect = true;
					break;
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		if (isCorrect) {
			score += 10 + bonusScore;
			++correctAnswer;
			scoreView.setText("" + score);
			imageView.setImageBitmap(ret);
			quizeButton.setBackgroundResource(R.drawable.quiz_answer_correct);
			Utils.play(RecallQuizeActivity.this, R.raw.sound_correct);
			if (isTimer) {
				whatView.setText(bonusScore + " Bonus points");
			}
		} else {
			score += 0;
			scoreView.setText("" + score);
			// imageView.setImageResource(partImageId);
			imageView.setImageBitmap(ret);
			quizeButton.setBackgroundResource(R.drawable.quiz_answer_wrong);
			Utils.play(RecallQuizeActivity.this, R.raw.sound_incorrect);
			Utils.vibratePhone(RecallQuizeActivity.this);
		}
		isNextQuestion = true;
		isClick = false;
		if (!isPinDrop) {
			dropPin();
		}

		if (isTimer) {
			try {
				new AsyncTask<String, String, String>() {
					@Override
					protected void onPreExecute() {
						try {
							iquize.cancel(true);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					protected String doInBackground(String... arg0) {
						try {
							Log.i("DREG", "Quize index =" + quizeIndex);
							if (quizeIndex < (numOfQuestion - 2)) {
								Thread.sleep(Constants.WAITING_FOR_NEXT);
							} else {
								Thread.sleep(500);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(String unused) {

						// dropPin();
						if (quizeIndex < (numOfQuestion - 2)) {
							iquize = new ImplementQuiz(++quizeIndex,
									Constants.WAITING_TIME);
						} else {
							iquize = new ImplementQuiz(++quizeIndex, 0);
						}
						iquize.execute();
					}
				}.execute();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		// isCorrect = false;
		// JSONArray points = items.get(targetPosition[currentIndex]);
		//
		// for (int i = 0; i < points.length(); i++) {
		// try {
		// int x1 = (int) (points.getJSONObject(i).getInt("-x1") * factor);
		// int x2 = (int) (points.getJSONObject(i).getInt("-x2") * factor);
		// int y1 = (int) (points.getJSONObject(i).getInt("-y1") * factor);
		// int y2 = (int) (points.getJSONObject(i).getInt("-y2") * factor);
		//
		// if (posX >= x1 && posX <= x2) {
		// if (posY >= y1 && posY <= y2) {
		// isCorrect = true;
		// break;
		// }
		//
		// }
		//
		// } catch (JSONException e) {
		// e.printStackTrace();
		// }
		// }
		//
		// if (isCorrect) {
		// score += 10 + bonusScore;
		// scoreView.setText("" + score);
		// for (int j = 0; j < files.length; j++) {
		// if (files[j].getName().equalsIgnoreCase(partFileName + ".png")) {
		//
		// Bitmap bm = BitmapFactory.decodeFile(files[j]
		// .getAbsolutePath());
		// Bitmap ret = Bitmap.createBitmap(imageViewWidth,
		// imageViewHeight, Bitmap.Config.ARGB_8888);
		// Canvas comboImage = new Canvas(ret);
		// Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
		// Rect r2 = new Rect(0, 0, imageViewWidth, imageViewHeight);
		// comboImage.drawBitmap(bm, r1, r2, null);
		// comboImage.save();
		// imageView.setImageBitmap(ret);
		// }
		// }
		// quizeButton.setBackgroundResource(R.drawable.quiz_answer_correct);
		// Utils.play(RecallQuizeActivity.this, R.raw.sound_correct);
		// } else {
		// score += 0;
		// scoreView.setText("" + score);
		//
		// for (int j = 0; j < files.length; j++) {
		// if (files[j].getName().equalsIgnoreCase(partFileName + ".png")) {
		//
		// Bitmap bm = BitmapFactory.decodeFile(files[j]
		// .getAbsolutePath());
		// Bitmap ret = Bitmap.createBitmap(imageViewWidth,
		// imageViewHeight, Bitmap.Config.ARGB_8888);
		// Canvas comboImage = new Canvas(ret);
		// Rect r1 = new Rect(0, 0, bm.getWidth(), bm.getHeight());
		// Rect r2 = new Rect(0, 0, imageViewWidth, imageViewHeight);
		// comboImage.drawBitmap(bm, r1, r2, null);
		// comboImage.save();
		// imageView.setImageBitmap(ret);
		//
		// }
		// }
		// quizeButton.setBackgroundResource(R.drawable.quiz_answer_wrong);
		// Utils.play(RecallQuizeActivity.this, R.raw.sound_incorrect);
		//
		// }
		//
		// isNext = true;
		// isClick = false;
		// if (!isPinDrop) {
		// dropPin();
		// }

	}

	private void animatePin(ImageView imageView, Bitmap bitmap, int animTime)
			throws Exception {

		imageView.setVisibility(View.VISIBLE);

		final TranslateAnimation anim = new TranslateAnimation(posX
				- bitmap.getWidth() / 2, posX - bitmap.getWidth() / 2,
				-bitmap.getHeight(), posY - bitmap.getHeight());

		anim.setDuration(animTime);
		anim.setFillAfter(true);
		anim.setAnimationListener(new Animation.AnimationListener() {
			@Override
			public void onAnimationStart(Animation arg0) {
			}

			@Override
			public void onAnimationRepeat(Animation arg0) {
			}

			@Override
			public void onAnimationEnd(Animation arg0) {
			}
		});
		imageView.startAnimation(anim);
		imageView.setImageBitmap(bitmap);

	}

	private void dropPin() {
		bitmap = BitmapFactory.decodeResource(getResources(),
				R.drawable.pin_drop);
		pinView = new ImageView(this);
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				bitmap.getWidth(), bitmap.getHeight());
		pinView.setLayoutParams(layoutParams);
		recallLayout.addView(pinView);
		if (isFirstTime) {
			pinView.setVisibility(View.GONE);
			isFirstTime = false;
		} else {
			pinView.setVisibility(View.INVISIBLE);
			try {
				animatePin(pinView, bitmap, Constants.PIN_ANIMTED_TIME);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		isPinDrop = true;
	}

	private JSONArray ja;
	private JSONObject jo;

	private void getPointsList(int level) {
		try {
			jo = new JSONObject(getJsonData(level));
			ja = jo.getJSONObject("root").getJSONArray("dog");
			for (int i = 0; i < ja.length(); i++) {
				JSONArray points = ja.getJSONObject(i).getJSONArray("points");
				items.add(points);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showPausePopUp() {
		isAnim = false;
		LayoutInflater factory = LayoutInflater.from(this);
		View dialog = factory.inflate(R.layout.layout_pause_screen, null);

		ImageView resumeView = (ImageView) dialog.findViewById(R.id.resumeView);
		Button menuButton = (Button) dialog.findViewById(R.id.menuButton);
		animView = (ImageView) dialog.findViewById(R.id.imageView);

		AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
		alt_bld.setCancelable(false);
		final AlertDialog alert = alt_bld.create();

		resumeView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// timer.start();
				// timer.onTick(bonusScore*1000);

				isPause = false;
				isNextQuestion = true;
				// if (isTimer) {
				// showTimer(remainingTime);
				// }
				// iquize = new ImplementQuiz(quizeIndex, remainingTime);
				// iquize.execute();
				iquize = new ImplementQuiz(quizeIndex, remainingTime);
				iquize.execute();

				alert.cancel();

			}
		});

		menuButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				isAnim = true;
				isExit = true;
				alert.cancel();
				Intent intent = new Intent(RecallQuizeActivity.this,
						RecallBeforeActivity.class);
				intent.putExtra(Constants.KEY_QUIZ, Constants.QUIZ_LEARNING);
				startActivity(intent);

			}
		});
		showImageInPeriod();
		alert.setView(dialog);
		alert.show();
	}

	private void showImageInPeriod() {
		try {
			new AsyncTask<String, String, String>() {
				private boolean isInvisible;
				private int index;

				@Override
				protected void onPreExecute() {
					try {
						index = 0;
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {
					animView.setBackgroundResource(imagesToShow[index]);

				}

				@Override
				protected String doInBackground(String... arg0) {
					try {
						while (!isAnim) {
							if (index < (imagesToShow.length - 1)) {
								index++;
							} else {
								index = 0;
							}
							publishProgress("");
							Thread.sleep(4000);

						}

					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void showQuizeAimation() {
		try {
			new AsyncTask<String, String, String>() {

				@Override
				protected void onPreExecute() {
					try {

						jo = new JSONObject(getJsonData(level));
						ja = jo.getJSONObject("root").getJSONArray("dog");

						nrr = new NoRepeatRandom(0, ja.length() - 1);
						targetPosition = new int[ja.length()];

						for (int i = 0; i < ja.length(); i++) {
							targetPosition[i] = nrr.GetRandom();
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected void onProgressUpdate(String... arg0) {
					try {

						if (isPinDrop) {
							ViewGroup vg = (ViewGroup) (pinView.getParent());
							vg.removeView(pinView);
							isPinDrop = false;
						}

						currentIndex++;
						quizeButton.setVisibility(View.VISIBLE);

						Log.i("DREG", "Current Index in onProgressupdate ="
								+ currentIndex);
						if (currentIndex != ja.length()) {
							if (isTimer) {
								showTimer(Constants.WAITING_TIME);
							}

							isClick = true;
							isNext = false;
							quesTextView.setText((currentIndex + 1) + "/"
									+ ja.length());

							quizeButton
									.setBackgroundResource(R.drawable.quize_button);
							quizeButton.setTextColor(Color.WHITE);
							quizeButton.setEnabled(true);
							String parentFile = ja.getJSONObject(
									targetPosition[currentIndex]).getString(
									"-parent")
									+ ".png";
							Log.i("DREG", "parent File Name=" + parentFile);

							for (int i = 0; i < files.length; i++) {
								if (files[i].getName().equalsIgnoreCase(
										parentFile)) {
									Bitmap bm = BitmapFactory
											.decodeFile(files[i]
													.getAbsolutePath());
									Bitmap ret = Bitmap.createBitmap(
											imageViewWidth, imageViewHeight,
											Bitmap.Config.ARGB_8888);
									Canvas comboImage = new Canvas(ret);
									Rect r1 = new Rect(0, 0, bm.getWidth(),
											bm.getHeight());
									Rect r2 = new Rect(0, 0, imageViewWidth,
											imageViewHeight);
									comboImage.drawBitmap(bm, r1, r2, null);
									comboImage.save();
									imageView.setImageBitmap(ret);
								}
							}

							partFileName = ja.getJSONObject(
									targetPosition[currentIndex]).getString(
									"-part");
							quizeButton.setText(partFileName);
						} else {
							timerView.setVisibility(View.GONE);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				@Override
				protected String doInBackground(String... arg0) {
					try {

						while ((currentIndex < ja.length()) && (!isExit)) {
							if (isTimer) {
								Random random = new Random();
								randomValue = random.nextInt(4);
								publishProgress("");
								Thread.sleep(Constants.WAITING_TIME);
							} else {
								if (isNext) {
									Random random = new Random();
									randomValue = random.nextInt(4);
									if (currentIndex != -1) {
										Thread.sleep(Constants.POST_CLICK_TIME);
									}
									publishProgress("");
									Thread.sleep(Constants.PRE_CLICK_TIME);

								}
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				@Override
				protected void onPostExecute(String unused) {

					if (!isExit) {
						int percent = (int) ((score * 100) / (ja.length() * 10));
						// quesTextView.setVisibility(View.GONE);
						imageView.setAlpha(0x7F);
						timerView.setText("0.0");
						quizeButton.setVisibility(View.INVISIBLE);
						mainMenuButton.setVisibility(View.VISIBLE);
						tryButton.setVisibility(View.VISIBLE);
						facebookButton.setVisibility(View.VISIBLE);
						twitterButton.setVisibility(View.VISIBLE);
						alertView.setVisibility(View.VISIBLE);
						// pauseView.setVisibility(View.INVISIBLE);
						if (percent < 70) {
							isNextLevel = false;
							alertView.setText("Sorry,you only scored \n"
									+ score + " points with " + percent
									+ "% accuracy.");
						}

						else {
							isNextLevel = true;
							tryButton.setText("Next Level");
							alertView
									.setText("Congratulations,you have scored "
											+ score + " points with " + percent
											+ "% accuracy.");
							int highestScore = Utils.getLevelHighestScore(
									RecallQuizeActivity.this,
									Constants.KEY_RECALL_SCORE + level);
							if (score < highestScore) {
								Utils.putLevelHighestScore(
										RecallQuizeActivity.this,
										Constants.KEY_RECALL_SCORE + level,
										score);
								Utils.putPrecentage(
										RecallQuizeActivity.this,
										Constants.KEY_RECALL_PERCENTAGE + level,
										percent);
							}

						}
					}
				}
			}.execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private JSONObject getJSONObjectForRandomLevel() {

		JSONObject randJob = new JSONObject();
		JSONArray dogA = new JSONArray();
		JSONObject rootJob = new JSONObject();
		try {
			JSONObject jo = new JSONObject(new String(Utils.getFileData(this,
					"Random Recall.json")));
			JSONArray ja = jo.getJSONObject("root").getJSONArray("dog");

			if (Utils.containsAllFiles(Constants.PACK1_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(RecallQuizeActivity.this,
							Constants.PACK1_JSON_FILE)))) {
				for (int i = 0; i < 49; i++) {
					JSONObject jOb = new JSONObject();

					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");

					JSONArray points = new JSONArray();
					points = ja.getJSONObject(i).getJSONArray("points");
					jOb.put("points", points);
					jOb.put("-part", part);
					jOb.put("-parent", parent);

					dogA.put(jOb);
				}
			}
			if (Utils.containsAllFiles(Constants.PACK2_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(RecallQuizeActivity.this,
							Constants.PACK2_JSON_FILE)))) {
				for (int i = 49; i < 94; i++) {

					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");

					JSONArray points = new JSONArray();
					points = ja.getJSONObject(i).getJSONArray("points");
					jOb.put("points", points);
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			if (Utils.containsAllFiles(Constants.PACK3_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(RecallQuizeActivity.this,
							Constants.PACK3_JSON_FILE)))) {
				for (int i = 94; i < 136; i++) {
					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					JSONArray points = new JSONArray();
					points = ja.getJSONObject(i).getJSONArray("points");
					jOb.put("points", points);
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			if (Utils.containsAllFiles(Constants.PACK4_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(RecallQuizeActivity.this,
							Constants.PACK4_JSON_FILE)))) {
				for (int i = 136; i < 170; i++) {
					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					JSONArray points = new JSONArray();
					points = ja.getJSONObject(i).getJSONArray("points");
					jOb.put("points", points);
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			if (Utils.containsAllFiles(Constants.PACK5_DIRECTORY, Arrays
					.asList(Utils.getImageFileName(RecallQuizeActivity.this,
							Constants.PACK5_JSON_FILE)))) {
				for (int i = 170; i < ja.length(); i++) {
					JSONObject jOb = new JSONObject();
					String part = ja.getJSONObject(i).getString("-part");
					String parent = ja.getJSONObject(i).getString("-parent");
					Log.i("DREG", "Random part name=" + part);
					Log.i("DREG", "Random parent name=" + parent);
					JSONArray points = new JSONArray();
					points = ja.getJSONObject(i).getJSONArray("points");
					jOb.put("points", points);
					jOb.put("-part", part);
					jOb.put("-parent", parent);
					dogA.put(jOb);
				}
			}

			randJob.put("dog", dogA);
			rootJob.put("root", randJob);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Log.i("DREG", "Root JSON=" + rootJob.toString());
		return rootJob;
	}

}
